package pri.damai.xiaowu.gateway.websocket;

import com.google.common.collect.Lists;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.WebsocketRoutingFilter;
import org.springframework.cloud.gateway.filter.headers.HttpHeadersFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import pri.damai.xiaowu.common.core.exception.GlobalException;
import pri.damai.xiaowu.common.core.util.ExceptionUtil;
import pri.damai.xiaowu.common.security.constant.AuthConstant;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * WebSocket 过滤器
 *
 * @description
 * @author YangXinFu
 * @date 11:18 2022/7/21
 **/
@Component
public class WebSocketFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        if (route == null) {
            return chain.filter(exchange);
        }

        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        List<String> params = queryParams.get("token");
        String token = null;
        if (!CollectionUtils.isEmpty(params)) {
            token = params.get(0);
        }

        ExceptionUtil.ifTureThrow(!StringUtils.hasText(token), "未携带 Token。");

        ServerHttpRequest request1 = exchange.getRequest().mutate()
                .header(AuthConstant.USER_ID_KEY, "1")
                .header(AuthConstant.USER_NAME_KEY, "testName")
                .build();
        exchange.mutate().request(request1).build();

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 9999;
    }
}
